// commonFunctions.js
import Decimal from "decimal.js"
import XLSX from "xlsx"
import clipboard3 from "vue-clipboard3"
import { ElMessage } from "element-plus"

// 根据每十万价格去算最终金额和贴息费用
// AmountType true 是按元去计算， false 是按万元去计算
const generatePrice = (
  price: number | undefined,
  finallyAmount: number | undefined,
  discountAmount: number | undefined,
  billAmount: string,
  AmountType: boolean
) => {
  // 将price转换为Decimal类型
  const priceDecimal = new Decimal(price || 0)
  // 如果price小于0，则返回[0, billAmount, 0]
  if (priceDecimal.toNumber() < 0) {
    return [0, billAmount, 0]
  }
  // 初始化prices为0
  let prices = new Decimal(0)
  // 将billAmount转换为Decimal类型
  const billAmounts = new Decimal(billAmount)
  if (AmountType) {
    // 贴息费： 票面金额除以10在除以10000,在乘以每十万的价格
    prices = billAmounts.div(10).div(10000).mul(priceDecimal)
    // 贴息费： 转为数字格式
    discountAmount = prices.round().toNumber()
    // discountAmount = prices.toDecimalPlaces(2).toNumber()
    // 最终价格：票面金额减去贴息费 最终价格：转为数字格式
    // finallyAmount = billAmounts.sub(prices).round().toNumber()
    finallyAmount = billAmounts.sub(prices).toDecimalPlaces(2).toNumber()
  } else {
    // 贴息费： 票面金额除以10,在乘以每十万的价格
    prices = billAmounts.div(10).mul(priceDecimal)
    // 贴息费： 转为数字格式
    discountAmount = prices.round().toNumber()
    // discountAmount = prices.toDecimalPlaces(2).toNumber()
    // 最终价格：票面金额乘10000减去贴息费 最终价格：转为数字格式
    // finallyAmount = billAmounts.mul(10000).sub(prices).round().toNumber()
    finallyAmount = billAmounts.mul(10000).sub(prices).toDecimalPlaces(2).toNumber()
  }

  return <any>{ price, finallyAmount, discountAmount }
}

// 根据贴息价格去算最终金额和每十万价格
// AmountType true 是按元去计算， false 是按万元去计算
const generateDiscount = (
  prices: number | undefined,
  finallyAmount: number | undefined,
  discountAmount: number | undefined,
  billAmount: string,
  AmountType: boolean
) => {
  // 声明一个Decimal类型的变量discountAmountDecimal，并将discountAmount的值赋值给discountAmountDecimal
  const discountAmountDecimal = new Decimal(discountAmount || 0)
  // 如果discountAmountDecimal的值小于0，则返回[0, billAmount, 0]
  if (discountAmountDecimal.toNumber() < 0) {
    return [0, billAmount, 0]
  }
  // 声明一个Decimal类型的变量billAmounts，并将billAmount的值赋值给billAmounts
  const billAmounts = new Decimal(billAmount)
  let price
  if (AmountType) {
    // 每十万价格=贴息成100000 除以票面金额
    price = discountAmountDecimal.mul(100000).div(billAmounts).toDecimalPlaces(2).toNumber()
    // 最终价格 =  票面金额 - 贴息金额
    finallyAmount = billAmounts.sub(discountAmountDecimal).toDecimalPlaces(2).toNumber()
  } else {
    // 每十万价格 : 贴息费乘 100000 在除以票面金额先乘10000
    price = discountAmountDecimal.mul(100000).div(billAmounts.mul(10000)).toDecimalPlaces(2).toNumber()
    //最终价格 ：票面金额乘 10000 减去 贴息金额
    finallyAmount = billAmounts.mul(10000).sub(discountAmountDecimal).toDecimalPlaces(2).toNumber()
    // finallyAmount = finallyAmount / 10000
  }

  return <any>{ price, finallyAmount, discountAmount }
}
// #region 计算二维数组某个元素值的和
const sumValuesForName = (array2D: string | any[], targetName: string) => {
  // 创建 Decimal 对象表示总和
  let total = new Decimal(0)

  // 遍历数据数组，累加到总和
  for (let i = 0; i < array2D.length; i++) {
    // 将每个元素转换为 Decimal 对象
    const currentDecimal = new Decimal(array2D[i][targetName] || 0)
    // 累加到总和
    total = total.plus(currentDecimal)
  }

  if (["enter_discount", "out_discount"].includes(targetName)) {
    // 四舍五入，不留小数点
    total = total.round()
  }

  const result = total.toNumber()
  return result
}
// #endregion

// 导出列表数据
// headers为头部值，data值为内容
const frontExport = (data: any, headers: any) => {
  // 创建新的工作簿
  const wb = XLSX.utils.book_new()
  // 将数据转换为工作表
  // const ws = XLSX.utils.json_to_sheet(data, { header: headers })
  const ws = XLSX.utils.aoa_to_sheet([headers, ...data])
  console.log(ws)
  console.log(typeof ws)
  console.log(data.length)
  for (let index = 1; index <= data.length + 1; index++) {
    if (index == 1) continue
    ws["D" + index].t = "n"
    // ws["H" + index].t = "n"
    // ws["I" + index].t = "n"
    // ws["N" + index].t = "n"
    // ws["O" + index].t = "n"
    // ws["P" + index].t = "n"
  }

  // 将工作表添加到工作簿中
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1")
  // 导出Excel文件
  XLSX.writeFile(wb, "票据管理.xlsx")
}

//#region 复制文字
const { toClipboard } = clipboard3()
const copyToClipboard = async (string: string) => {
  if (string == "") {
    return ""
  }
  try {
    await toClipboard(string)
    console.log("复制的text: ")
    ElMessage.success("复制成功")
  } catch (error) {
    console.log("复制失败!!")
    ElMessage.error("复制失败")
  }
}
//#endregion

export const sumValues = (list: any[]) => {
  const total = {
    billAmount: "",
    interestDeduction: "",
    rebate: ""
  }
  list.forEach((item: any, _) => {
    const billAmountDecimal = new Decimal(item.billAmount || 0)
    const BillAmount = new Decimal(total.billAmount || 0)
    const rebateDeduction = new Decimal(total.rebate || 0)
    const InterestDeduction = new Decimal(total.interestDeduction || 0)
    const openDecimal = new Decimal(item.open || 0)
    const points = new Decimal(item.points || 0)
    total.billAmount = billAmountDecimal.mul(10000).mul(openDecimal).plus(BillAmount).toString()
    total.interestDeduction = points
      .mul(openDecimal)
      .mul(billAmountDecimal)
      .div(100)
      .mul(10000)
      .plus(InterestDeduction)
      .toString()
    total.rebate = points.mul(openDecimal).mul(billAmountDecimal).div(100).mul(10000).plus(rebateDeduction).toString()
  })

  return total
}

export { generatePrice, generateDiscount, sumValuesForName, frontExport, copyToClipboard }
